<?php

namespace App\Http\Controllers\api\WeChat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class MiniProgramController extends Controller
{
    public function code2Session(Request $request)
    {
        $app = app('wechat.mini_program');
        $authData = $app->auth->session($request->input('js_code'));

        \Log::info($authData);
        if (isset($authData['openid']) && isset($authData['session_key'])) {
            return response()->json([
                'status' => 0,
                'message' => 'OK',
                'openid' => $authData['openid'],
                'session_key' => $authData['session_key'],
                'unionid' => isset($authData['unionid']) ? $authData['unionid'] : ""
            ]);
        } else {
            return response()->json([
                'status' =>  -1,
                'message' => isset($authData['errmsg']) ? $authData['errmsg'] : "系统错误，请联系管理员",
            ]);
        }
    }

    public function decryptData(Request $request)
    {
        $app = app('wechat.mini_program');
        $decryptedData = $app->encryptor->decryptData(
            $request->input('session'),
            $request->input('iv'),
            $request->input('encryptedData')
        );
        \Log::info($decryptedData);
        return response()->json([
            'status' => 0,
            'message' => 'OK',
            'phoneNumber' => $decryptedData['phoneNumber'],
            'purePhoneNumber' => $decryptedData['purePhoneNumber'],
            'countryCode' => $decryptedData['countryCode'],
        ]);
    }
}
